import { stringify } from 'querystring';
import { history } from 'umi';
import { fakeAccountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
// export default {
//   namespace: 'todo',//model中的effect和reducer要通过命名空间调用，不要和其他model同名
//   state: { }, //state,跟react组件中的state差不多一个意思
//   effects: { },//effect通常是调用服务端接口，后调用reducer更新state
//   reducers: { } //state通过reducer来更新
//   }
// // 生成器
// function *createIterator() {
//   yield 1;
//   yield 2;
//   yield 3;
//   }

//   // 生成器能像正规函数那样被调用，但会返回一个迭代器，迭代器对象拥有一个叫做next的方法来帮助你重启generator函数并得到下一个值
//   let iterator = createIterator();
//   console.log(iterator.next().value); // 1
//   console.log(iterator.next().value); // 2
//   console.log(iterator.next().value); // 3

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    
    // *表示生成器，处理异步，在程序中并不会因为是异步获取数据而暂停后面代码,
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      }); // Login successfully

      if (response.status === 'ok') {
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;

        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }

        history.replace(redirect || '/');
      }
    },

    logout() {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note
        sessionStorage.setItem('token','')
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
